package com.webapp.schedule;

import com.inforim.cognos.CognosClient;
import com.inforim.cognos.plugins.CognosReportPlugin;
import com.inforim.cognos.utils.CognosHelper;
import com.inforim.util.DESUtil;
import com.webapp.cognos.CogOpt;
import com.webapp.loader.XmlReportsLoader;
import com.webapp.mail.SendMail;
import com.webapp.module.CogUser;
import com.webapp.module.MailSubscriber;
import com.webapp.module.Report;
import com.webapp.util.BaseLog;
import com.webapp.util.Jcopy;
import com.webapp.util.PathRule;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.security.auth.login.LoginException;


public class HKRXSchedule extends BaseLog {
	private static Object debug;
	private static LinkedList reportLose;

	private static String getMailSubscriber(
			CognosReportPlugin cognosReportPlugin, String searchpath,
			String defaultMailTo) {
		StringBuffer emailto = new StringBuffer(defaultMailTo);
		CogOpt cp = new CogOpt();
		cp.getRolePerFromCogObj(cognosReportPlugin.getClient(), searchpath);
		// cognosReportPlugin.getRolePerFromCogObj(searchpath);
		List userlist = cp.getUserlist();
		Iterator iter = userlist.iterator();
		CogUser cu = null;
		while (iter.hasNext()) {
			if (emailto.length() > 0) {
				emailto.append(',');
			}
			cu = (CogUser) iter.next();
			String email=cu.getCoguser_email().trim();
			//去除空格
			email=email.replaceAll(" ", "");
			emailto.append(email);
		}
		return emailto.toString();
	}

	public static void main(String[] args) {
		logger.info("=================Begin Schedule=================");
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DATE, -1); // DATE=5 前一天
		String format = null;
		String[] reportid = new String[0];
		String attachfile = null;
		debug = null;
		// 处理传入参数的方法
		for (int idx = 0; idx < args.length; ++idx) {
			if (args[idx].compareTo("-year") == 0) {
				int runyear = Integer.parseInt(args[(idx + 1)]);
				cal.set(1, runyear);
			} else if (args[idx].compareTo("-month") == 0) {
				int runmonth = Integer.parseInt(args[(idx + 1)]);
				cal.set(2, runmonth - 1);
			} else if (args[idx].compareTo("-day") == 0) {
				int runday = Integer.parseInt(args[(idx + 1)]);
				cal.set(5, runday);
			} else if (args[idx].compareTo("-format") == 0) {
				format = args[(idx + 1)];
			} else if (args[idx].compareTo("-reportid") == 0) {
				reportid = args[(idx + 1)].split(",");
			} else if (args[idx].compareTo("-attachfile") == 0) {
				attachfile = args[(idx + 1)];
			} else if (args[idx].compareTo("-debug") == 0) {
				debug = args[(idx + 1)];
			} else {
				System.out.println("Unknown argument: " + args[idx]);
				System.exit(0);
			}
			++idx;
		}

		XmlReportsLoader reportsloader = new XmlReportsLoader();
		reportsloader.load();
		Map reports = reportsloader.getReportList();

		String Cognos_URL = XmlReportsLoader.getC8_URL();
		String userName = XmlReportsLoader.getC8_USERNAME();
		String userPassword = XmlReportsLoader.getC8_PASSWORD();
		String userNamespace = XmlReportsLoader.getC8_NAMESPACE();
		String Cognos_version = XmlReportsLoader.getC_VERSION();
		boolean authentication = true;
		if ((userName == null) || userName.equals("")) {
			authentication = false;
		} else {
			authentication = true;
			try {
				DESUtil desUtil = new DESUtil();
				userPassword = desUtil.decrypt(userPassword);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				logger.error("password decrypt error!");
			}
		}
		CognosClient cognosClient = CognosHelper.getClient();
		cognosClient.setDispatch(Cognos_URL);
		cognosClient.setUsername(userName);
		cognosClient.setPassword(userPassword);
		cognosClient.setNamespace(userNamespace);
		try {
			cognosClient.logon();
			// System.out.println("logon success!");
		} catch (LoginException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error("Connect to Cognos failed, please check username & pasword in config.xml or Cognos enviroment.");
			return;
		}

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String paramString = "date=" + sdf.format(cal.getTime())
				+ "T00:00:00.000";

		Report report = null;
		MailSubscriber subscriber = null;

		reportLose = new LinkedList();

		List attachfiles = new ArrayList();

		for (int i = 0; (reportid != null) && (i < reportid.length); ++i) {
			report = (Report) reports.get(reportid[i]);
			runReport(cognosClient, report, format, cal, paramString,
					subscriber, attachfiles, attachfile);
		}
		List<Report> nextRetry = new ArrayList<Report>();
		while (true) {
			report = (Report) reportLose.poll();
			if (report == null) {
				break;
			}
			if (report.getRetryNum() >= 3) {
				nextRetry.add(report);
				continue;
			}
			report.addRetry();
			runReport(cognosClient, report, format, cal, paramString,
					subscriber, attachfiles, attachfile);
		}
		cognosClient.logoff();// 登出
		// 输出失败信息
		logger.info("==========Schedule finished!Result as follow,========");
		logger.info("==========Failed list:");
		for (int i = 0; i < nextRetry.size(); i++) {
			report = (Report) nextRetry.get(i);
			logger.info("ReportId:\"" + report.getId() + "\" send fail!");
			logger.info("    Report:" + report.getPrefixFilename());
			logger.info("    ReportSearchPath:" + report.getSearchpath());
		}
		logger.info("======================end=============================");

	}

	private static void runReport(CognosClient cognosClient, Report report,
			String format, Calendar cal, String paramString,
			MailSubscriber subscriber, List attachfiles, String attachfile) {
		// TODO Auto-generated method stub

		boolean isOK = false;
		try {
			CognosReportPlugin cognosReportPlugin = CognosHelper
					.getReportPlugin();
			cognosReportPlugin.setClient(cognosClient);
			String path = PathRule.getHKSavePath(report.getSavefolder());

			String tempformat = null;
			if (format != null)
				tempformat = format;
			else {
				tempformat = report.getFileFormat();
			}
			String fileName = "";
			fileName = PathRule.getHKReportName(report.getPrefixFilename(),
					cal.getTime(), tempformat);
			logger.info("Running the report...ReportId:"+report.getId());
			logger.info("Report search path is:" + report.getSearchpath());

			long beginTime = System.currentTimeMillis();
			isOK = cognosReportPlugin.runReport(null, null,
					report.getSearchpath(), paramString, path + fileName, null);
			long endTime=System.currentTimeMillis();
			logger.info("Running report has used "+(endTime-beginTime)/1000+"sec!");
			if (!(isOK)) {
				reportLose.offer(report);
				logger.info("Report running failure! Add to failure queue and retry later! reportId:"+ report.getId()+" searchpath:"+report.getSearchpath());
			} else {
				logger.info("Report running success! Report has exported on server "+path+fileName);
//				subscriber = report.getMail();
//				getMailSubscriber(cognosReportPlugin, report.getSearchpath(),
//						subscriber.getTo());
				logger.info("Email sending....");
				// Jcopy.CopyFile(runreport.getSaveLocation() + File.separator +
				// runreport.getFileName(), report.getCopyfolder());
				Jcopy.CopyFile(path + fileName, report.getCopyfolder()); // 复制到网盘上
				// 邮件内容
				SendMail mail = new SendMail();
				mail.setSMTPHost(XmlReportsLoader.getMAIL_HOST());
				mail.setUser(XmlReportsLoader.getMAIL_USER());
				mail.setPassword(XmlReportsLoader.getMAIL_PWD());
				subscriber = report.getMail();
				mail.setFrom(subscriber.getFrom());
				if (debug != null && debug.equals("true")) {
					mail.setTo("cz902811@gsk.com");
//				} else if(null!=subscriber.getTo()&&!subscriber.getTo().equals("")){
//					mail.setTo(subscriber.getTo());
				}else{
					mail.setTo(getMailSubscriber(cognosReportPlugin,
							report.getSearchpath(), subscriber.getTo()));
				}

				mail.setSubject(subscriber.getSubject());
				mail.setContent(subscriber.getContent());

				boolean isAttach = false;
				if (attachfile != null)
					isAttach = Boolean.parseBoolean(attachfile);
				else {
					isAttach = subscriber.isAttachfile();
				}
				if (isAttach) {
					attachfiles.clear();
					// attachfiles.add(runreport.getSaveLocation() +
					// File.separator + runreport.getFileName());
					attachfiles.add(path + fileName);
					mail.setFileList(attachfiles);
				}

//				isOK = mail.send();
				if (!(isOK)) {
					reportLose.offer(report);
					logger.info("Report Sending failure! Add to failure queue! reportId:"
							+ report.getId());
				} else {
					logger.info("Report Sending success! reportId:"
							+ report.getId());
				}

			}

			// cmService.logoff();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}